package cn.zyl.demo.undertow;

import io.undertow.servlet.spec.RequestDispatcherImpl;
import io.undertow.servlet.spec.ServletContextImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * DemoUndertowApplication类说明: 启动类
 * <p><a href="https://www.cnblogs.com/duanxz/p/9337022.html">Spring Boot 内嵌容器Undertow参数设置</a></p>
 * <pre>
 *     轻量级：它是一个 Web 服务器，但不像传统的 Web 服务器有容器概念，它由两个核心 Jar 包组成，加载一个 Web 应用可以小于 10MB 内存
 *     Servlet3.1 支持：它提供了对 Servlet3.1 的支持
 *     WebSocket 支持：对 Web Socket 完全支持，用以满足 Web 应用巨大数量的客户端
 *     嵌套性：它不需要容器，只需通过 API 即可快速搭建 Web 服务器
 * </pre>
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-01
 */
@SpringBootApplication
public class DemoUndertowApplication  extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        System.out.println("++++++++++++SpringBootServletInitializer");
        return application.sources(DemoUndertowApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoUndertowApplication.class, args);
    }
    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        // 用于运行bean的回调
        return args -> {
            String[] beanNames = ctx.getBeanDefinitionNames();
            //Arrays.sort(beanNames);
            //Arrays.stream(beanNames).forEach(System.out::println);
            System.out.println("<<<<<SpringBoot 默认为我们提供的 Bean-size:"+beanNames.length);
        };
    }
    @Bean
    public RequestDispatcherImpl initRequestDispatcherImpl(ServletContextImpl context){
        System.out.println("手动注册----RequestDispatcherImpl");
        return new RequestDispatcherImpl(context.getDeployment().getServletPaths().getServletHandlerByPath("/").getServletChain(), context);
    }
    /**配置undertow*/
    @Bean
    public UndertowServletWebServerFactory embeddedServletContainerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        //监听多个端口
        factory.addBuilderCustomizers(builder -> builder.addHttpListener(8090, "0.0.0.0"));
        //factory.setJsp();
        //启用http2
        //builder. setServerOption(UndertowOptions.ENABLE_HTTP2, true);
        //启用server push
        //builder. setServerOption(UndertowOptions.HTTP2_SETTINGS_ENABLE_PUSH, true);
        return factory;
    }
}
